<?php

namespace App\Exports\Plane;

use App\Models\Common\Area\Repositories\Interfaces\AreaRepositoryInterface;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\FromCollection;

class CitiesByCityJsonExport implements FromCollection
{
    /**
     * @return Collection
     */
    public function collection()
    {
        $plane_cities = file_get_contents(storage_path('plane/city.json'));
        $cities       = json_decode(json_decode($plane_cities, true), true);

        $collect  = collect($cities['cities'])->values()->flatten(1)
                                              ->where('countryName', "中国");
        $areaRepo = app(AreaRepositoryInterface::class);
        $res      = $collect->map(function ($city) use ($areaRepo) {
            $area = $areaRepo->findByName($city['cityName']);
            if (!$area) {
                $area = $areaRepo->fuzzyFind($city['cityName'], 'city');
            }
            if (!$area) {
                $area = $areaRepo->fuzzyFind($city['cityName'], 'district');
            }

            if ($area) {

            }

            return [
                'code'       => $city['cityCode'],
                'name'       => $city['cityName'],
                'name_uy'    => '',
                'adcode'     => $area?->getAdCode() ?: '',
                'adname'     => $area?->getAreaName() ?: '',
                'adname_uy'  => $area?->getAreaNameUy() ?: '',
                'initial_uy' => $area?->getLetterUy() ?: '',
            ];
        })->toArray();
        $head     = [
            '城市码',
            '城市名称',
            '城市翻译',
            '区域码',
            '匹配城市',
            '匹配城市翻译',
            '匹配城市首字母',
        ];

        array_unshift($res, $head);
        return collect($res);
    }
}
